$(document).ready(function() {
	warehouseTree("mytree", "#mytreeContent", function(event, treeId, treeNode, clickFlag) {
		//如果当前节点没有父节点
		if (treeNode.isParent == false) {

			//var s=zztree.getNodesByParam("Name", "MISUMI", null);
			//alert("treeNode.Name : " + treeNode.Name + " , treeNode.Id : " + treeNode.Id);
			//alert(treeNode.getParentNode().Name);

		} else {
			alert("此节点为父节点，不能选择！");
		}

	}, function(event, treeId, treeNode, msg) {

		var wtree = $.fn.zTree.getZTreeObj("mytree");
		//wtree.destroy();
		var sss = wtree.getNodeByParam("Name", "塑料粒子", null);
		//var sss = wtree.getNodes();
		alert(sss.Fid);
	});



});

function warehouseTree(treeId, appendToDomId, onClick, onAsyncSuccess) {
	var zTree = null,
		rMenu = null,
		oldTreeNodeName = "",
		$rMenu = null,
		addCount = 1;

	//鼠标点击事件
	var onBodyMouseDown = function(event) {
		if (!(event.target.id == "tree-rMenu" || $(event.target).parents("#tree-rMenu").length > 0)) {
			removeRMenu();
		}
	};

	//创建右键菜单
	var createRMenu = function(type, x, y) {
		$("#tree-rMenu").remove();
		$rMenu = $("<ul id=\"tree-rMenu\" class=\"dropdown-menu tree-rMenu\"><li id=\"m_add\"><a href=\"#\">增加</a></li><li id=\"m_rename\"><a href=\"#\">重命名</a></li><li id=\"m_del\"><a href=\"#\">删除</a></li></ul>");
		if (type == "root") {
			$rMenu.find("#m_del").remove();
			$rMenu.find("#m_rename").remove();
		}
		$rMenu.css({
			"top": y + "px",
			"left": x + "px"
		}).addClass("show").appendTo("body");

		$("body").bind("mousedown", onBodyMouseDown);
	};

	//删除右键菜单
	var removeRMenu = function() {
		if ($rMenu) {
			$rMenu.remove();
		}
		$("body").unbind("mousedown", onBodyMouseDown);
	};

	//修改节点名称
	var editTreeNode = function(nNode) {
		removeRMenu();
		if (nNode) {
			oldTreeNodeName = nNode.Name;
			zTree.editName(nNode);
		}
	};

	//获取节点，并且编辑这个节点
	var getAndEditNode = function(zTree, fNode) {
		var nNode = zTree.getNodeByParam("temp", addCount, null);
		nNode.temp = 0; //先把addCount临时保存到temp中，然后通过addCount找到这个节点，再把temp归零
		nNode.Ev = 0; //表示新增分类
		if (fNode) {
			nNode.Fid = fNode.Id;
		} else {
			nNode.Fid = "0";
		}
		editTreeNode(nNode);
		addCount++;
	};

	//添加树节点
	var addTreeNode = function() {
		removeRMenu();
		var newNode = {
			Name: "新增" + addCount,
			temp: addCount
		};
		oldTreeNodeName = newNode.Name;
		var fNode = zTree.getSelectedNodes()[0];
		if (fNode) {
			zTree.addNodes(fNode, newNode);
			getAndEditNode(zTree, fNode);
		} else {
			zTree.addNodes(null, newNode);
			getAndEditNode(zTree, fNode);
		}
	};


	//删除节点
	var removeTreeNode = function(nNodes) {

		if (nNodes[0].children && nNodes[0].children.length > 0) { //有子节点
			nNodes[0].Re = 1;
			//alert("f   ID："+nNodes[0].Id);
			//beforeRemove("tree", nNodes[0]);

			zTree.removeNode(nNodes[0]);
		} else { //没有子节点
			nNodes[0].Re = 0;
			//alert("z   ID："+nNodes[0].Id);
			//beforeRemove("tree", nNodes[0]);

			zTree.removeNode(nNodes[0]);
		}

	};

	//弹出一个简单的对话框
	var simpleDialog = function(contentStr) {
		$("body").append($("<div id=\"ztree-simple-dialog\"></div>"));
		$("#ztree-simple-dialog").dialog({
			content: contentStr,
			showBtn: false
		});
		setTimeout(function() {
			$("#ztree-simple-dialog").dialog("close");
		}, 3000);
	};

	//ztree onRightClick回调函数
	var onRightClick = function(event, treeId, treeNode) {
		if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
			zTree.cancelSelectedNode();
			createRMenu("root", event.pageX, event.pageY);
		} else if (treeNode && !treeNode.noR) {
			zTree.selectNode(treeNode);
			createRMenu("node", event.pageX, event.pageY);
		}
	};

	//ztree beforeRename回调函数
	var beforeRename = function(treeId, treeNode, newName, isCancel) {
		if (newName.length == 0) {
			alert("节点名称不能为空.");
			return false;
		} else {
			treeNode.Name = newName;
			if (treeNode.Ev == 0) { //如果Ev=0，创建新分类
				if (isCancel == true) { //按ESC键删除刚创建的treeNode
					zTree.removeNode(treeNode);
				} else {
					var data = postData(JSON.stringify(treeNode), "/green/warehouse/create");
					if (data.Status == 1) { //数据库操作出错
						treeNode.Name = oldTreeNodeName;
						if (isCancel == true) { //按下ESC键删除对话框并且取消编辑
							$("#ztree-simple-dialog").remove();
						} else {
							if ($("#ztree-simple-dialog").length < 1) { //如果DOM中没有该对象，弹出对话框
								simpleDialog("数据库出错，请检查数据库设置！");
							}
							return false;
						}
					} else {
						treeNode.Id = data.Data;
						zTree.updateNode(treeNode);
					}
				}

			} else { //如果Ev!=0，更新分类
				var data = postData(JSON.stringify(treeNode), "/green/warehouse/update");
				//var data = new Object();
				//data.Status = 1;
				if (data.Status == 1) { //数据库就操作出错
					treeNode.Name = oldTreeNodeName;
					if (isCancel == true) { //按下ESC键删除对话框并且取消编辑
						$("#ztree-simple-dialog").remove();
					} else {
						if ($("#ztree-simple-dialog").length < 1) { //如果DOM中没有该对象，弹出对话框
							simpleDialog("数据库出错，请检查数据库设置！");
						}
						return false;
					}
				} else {
					zTree.updateNode(treeNode); //更新Node
				}
			}
		}
		return true;
	};

	// var zTreeOnAsyncSuccess = function(event, treeId, treeNode, msg) {
	// 	alert(msg);
	// };

	//ztree添加一个新节点
	$(document).on("click", "#m_add", function() {
		addTreeNode();
	});

	//ztree修改一个节点名称
	$(document).on("click", "#m_rename", function() {
		var nNode = zTree.getSelectedNodes()[0];
		nNode.Ev = 1; //表示更新分类
		editTreeNode(nNode);
	});

	//ztree删除一个节点
	$(document).on("click", "#m_del", function() {
		var nNodes = zTree.getSelectedNodes();
		if (nNodes && nNodes.length > 0) {
			var isParent = nNodes[0].isParent;
			//alert(isParent);
			if (isParent == false) { //不是父节点，直接删除
				//隐藏右键菜单 -> 增加删除对话框 -> 点击确认按钮删除
				removeRMenu();
				$("body").append($("<div id=\"ztree-del-dialog\"></div>"));
				$("#ztree-del-dialog").dialog({
					mask: true,
					title: "删除分类",
					content: "你真的要删除这个分类吗？",
					ok: function() {
						$("#ztree-del-dialog").dialog("close");
						removeTreeNode(nNodes);
					}
				});
			} else {
				//隐藏右键菜单 -> 增加删除对话框 -> 点击确认按钮删除
				removeRMenu();
				$("body").append($("<div id=\"ztree-del-dialog\"></div>"));
				$("#ztree-del-dialog").dialog({
					mask: true,
					title: "删除分类",
					content: "object:#tree-r-del-content",
					ok: function() {
						$("#ztree-del-dialog").dialog("close");
						removeTreeNode(nNodes);
					}
				});
			}

		}
	});

	$("<ul id=\"" + treeId + "\" class=\"ztree\"></ul>").appendTo(appendToDomId);
	//初始化ztree
	var setting = {
		edit: {
			enable: true,
			showRemoveBtn: false,
			showRenameBtn: false
		},
		async: {
			enable: true,
			url: "/green/warehouse/list"
		},
		data: {
			key: {
				name: "Name"
			},
			simpleData: {
				enable: true,
				idKey: "Id",
				pIdKey: "Fid",
				rootPId: 0
			}
		},
		callback: {
			beforeRename: beforeRename,
			onClick: onClick,
			onRightClick: onRightClick,
			onAsyncSuccess: onAsyncSuccess
		}
	};
	$.fn.zTree.init($("#" + treeId), setting);
	zTree = $.fn.zTree.getZTreeObj(treeId);
	//alert(zTree.getNodes());
	//return zTree;
}